﻿// ********************************************************************************************
using B.MESUI.Login; // 引入分页控件命名空间
using B.MESUI.Login.ProdManagement.WorkOrder;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid; // 新增命名空间
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using B.MESUI.Login.A_Public.Constants;
using B.MESUI.Login.A_Public.Helpers;

namespace B.MESUI.Login
{
    public partial class YSL : DevExpress.XtraEditors.XtraForm
    {
        //private PaginationControl paginationControl;
        private int _pageSize = 10; // 默认每页条数
        private int _totalCount = 0;

        public YSL()
        {
            InitializeComponent();
            this.Load += YSL_Load;
        }

        private async void YSL_Load(object sender, EventArgs e)
        {

            panelControl2.Controls.Clear();

            // 设置GridView为多选模式（CheckBoxRowSelect）
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CheckBoxRowSelect;

            // 首次加载第一页数据
            await LoadDataByPageAsync(1, _pageSize);
        }



        private async Task LoadDataByPageAsync(int page, int pageSize)
        {
            try
            {
                var data = await GetWorkOrderListAsync(page, pageSize);
                if (data != null && data.pageDatas != null)
                {
                    gridControl1.DataSource = data.pageDatas;
                    _totalCount = data.totalCount;
                    // 设置时间列格式化
                    gridView1.Columns["START_TIME"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                    gridView1.Columns["START_TIME"].DisplayFormat.FormatString = "yyyy-MM-dd";
                    gridView1.Columns["END_TIME"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                    gridView1.Columns["END_TIME"].DisplayFormat.FormatString = "yyyy-MM-dd";
                   
                }
                else
                {
                    MessageBox.Show("未获取到工单数据！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取工单数据失败：" + ex.Message);
            }
        }

        private async Task<WorkOrderListResponse> GetWorkOrderListAsync(int page = 1, int pageSize = 10)
        {
            var endpoint = ApiEndpoints.WorkOrder.GetWorkOrderList;
            var url = HttpClientHelper.GetWorkOrderUrl(endpoint);
            var parameters = new Dictionary<string, object>
            {
                { "PageIndex", page },
                { "PageSize", pageSize }
            };
            var queryString = HttpClientHelper.BuildQueryString(parameters);
            if (!string.IsNullOrEmpty(queryString))
                url += "?" + queryString;
            var response = await HttpClientHelper.GetAsync(url);
            return JsonConvert.DeserializeObject<WorkOrderListResponse>(response);
        }

        // 获取所有选中行的WORKORDERID
        private List<string> GetSelectedWorkOrderIds()
        {
            var selectedRowHandles = gridView1.GetSelectedRows();
            List<string> selectedIds = new List<string>();

            foreach (var handle in selectedRowHandles)
            {
                var id = gridView1.GetRowCellValue(handle, "WORKORDERID")?.ToString();
                if (!string.IsNullOrEmpty(id))
                {
                    selectedIds.Add(id);
                }
            }
            return selectedIds;
        }

        // 删除按钮点击事件
        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            var selectedIds = GetSelectedWorkOrderIds();
            if (selectedIds.Count == 0)
            {
                MessageBox.Show("请先选择要删除的工单！");
                return;
            }

            var result = MessageBox.Show(
                $"确定要删除选中的{selectedIds.Count}条工单吗？",
                "删除确认",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                await DeleteWorkOrdersAsync(selectedIds);

            }

        }

        // 调用后端批量删除接口
        private async Task DeleteWorkOrdersAsync(List<string> workOrderIds)
        {
            try
            {
                var endpoint = ApiEndpoints.WorkOrder.DeleteWorkOrder;
                var url = HttpClientHelper.GetWorkOrderUrl(endpoint);
                var payload = new { WORKORDERIDS = workOrderIds };
                var response = await HttpClientHelper.PutAsync(url, payload);
                if (!string.IsNullOrEmpty(response))
                {
                    MessageBox.Show("删除成功！");
                    await LoadDataByPageAsync(1, _pageSize);
                }
                else
                {
                    MessageBox.Show("删除失败：无返回内容");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除失败：" + ex.Message);
            }
        }

        // 数据模型
        public class WorkOrderListResponse
        {
            public int totalCount { get; set; }
            public int totalPage { get; set; }
            public List<WorkOrder> pageDatas { get; set; }
            public int code { get; set; }
            public string message { get; set; }
            public object resultData { get; set; }
        }

        public class WorkOrder
        {
            public string WORKORDERID { get; set; }
            public string CODEID { get; set; }
            public string WORKORDER_TYPE { get; set; }
            public string PRODUCT_DATA { get; set; }
            public string PROCESS_ROUTE { get; set; }
            public string PRODUCTION_LINE { get; set; }
            public string WORK_STATUS { get; set; }
            public DateTime START_TIME { get; set; }
            public DateTime END_TIME { get; set; }
            public int NUMBER_COL { get; set; }
            public string WORKORDER_DESC { get; set; }
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void textEdit1_EditValueChanged(object sender, EventArgs e)
        {

        }

        private async void simpleButton4_Click(object sender, EventArgs e)
        {
            await LoadDataByPageAsync(1, _pageSize);
        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            AddWorkOrder addworkorder = new AddWorkOrder();
            if (addworkorder.ShowDialog() == DialogResult.OK)
            {
                await LoadDataByPageAsync(1, _pageSize);
            }
        }

        private async void seachworkorder_Click(object sender, EventArgs e)
        {
            string codeid = CODEID.Text.Trim();
            if (string.IsNullOrEmpty(codeid))
            {
                MessageBox.Show("请输入工单编号！");
                return;
            }
            await SearchWorkOrderByCodeIdAsync(codeid);
        }

        private async Task SearchWorkOrderByCodeIdAsync(string codeid)
        {
            try
            {
                var endpoint = ApiEndpoints.WorkOrder.GetWorkOrderList;
                var url = HttpClientHelper.GetWorkOrderUrl(endpoint);
                var parameters = new Dictionary<string, object>
                {
                    { "CODEID", codeid }
                };
                var queryString = HttpClientHelper.BuildQueryString(parameters);
                if (!string.IsNullOrEmpty(queryString))
                    url += "?" + queryString;
                var response = await HttpClientHelper.GetAsync(url);
                var data = JsonConvert.DeserializeObject<WorkOrderListResponse>(response);
                if (data != null && data.pageDatas != null)
                {
                    gridControl1.DataSource = data.pageDatas;
                    _totalCount = data.totalCount;
                }
                else
                {
                    MessageBox.Show("未获取到工单数据！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询失败：" + ex.Message);
            }
        }
    }
}



